<template>
	<view class="my-address">
		<!-- 地址列表 -->
		<scroll-view class="address-list" scroll-y>
			<view class="address-item" v-for="item in addressList" :key="item.id"
				:class="{ 'default-address': item.defaultAddress === 1 }">
				<view class="address-content">
					<view class="address-header">
						<text class="user-name">{{ item.userName }}</text>
						<text class="phone">{{ item.phone }}</text>
						<text class="default-tag" v-if="item.defaultAddress === 1">默认</text>
					</view>
					<view class="address-detail">{{ item.address }}</view>
				</view>
				<view class="address-actions">
					<button class="edit-btn" @click="editAddress(item.id)">修改</button>
					<button class="delete-btn" @click="deleteAddress(item.id)" v-if="addressList.length > 1">删除</button>
					<button class="set-default-btn" @click="setDefaultAddress(item.id)"
						v-if="item.defaultAddress !== 1">设为默认</button>
				</view>
			</view>
		</scroll-view>

		<!-- 底部添加按钮 -->
		<view class="add-btn-container">
			<button class="add-btn" @click="showAddDialog">添加新地址</button>
		</view>

		<!-- 添加/编辑地址弹窗 -->
		<uni-popup ref="addressDialog" type="dialog">
			<uni-popup-dialog mode="base" :title="dialogTitle" @confirm="submitAddress">
				<view class="address-form">
					<view class="form-row">
						<text class="form-label">收货人</text>
						<input class="form-input" v-model="form.userName" placeholder="请输入收货人姓名" />
					</view>

					<view class="form-row">
						<text class="form-label">手机号</text>
						<input class="form-input" v-model="form.phone" placeholder="请输入手机号" type="number" />
					</view>

					<view class="form-row">
						<text class="form-label">所在城市</text>
						<picker class="form-picker" @change="onCityChange" :value="cityIndex" :range="cities"
							range-key="name">
							<view class="picker-content">
								{{ form.cityId ? (cities.find(c => c.id === form.cityId) || {}).name || '请选择城市' : '请选择城市' }}
							</view>
						</picker>
					</view>

					<view class="form-row">
						<text class="form-label">所在区县</text>
						<picker class="form-picker" @change="onDistrictChange" :value="districtIndex" :range="districts"
							range-key="name" :disabled="!form.cityId">
							<view class="picker-content">
								{{ form.districtId ? (districts.find(d => d.id === form.districtId) || {}).name || '请选择区县' : '请选择区县' }}
							</view>
						</picker>
					</view>

					<view class="form-row">
						<text class="form-label">详细地址</text>
						<textarea class="form-textarea" v-model="form.address"
							placeholder="请输入街道、小区、门牌号等详细信息"></textarea>
					</view>

<!-- 					<view class="form-row switch-row">
						<text class="form-label">设为默认地址</text>
						<switch :checked="form.defaultAddress === 1" @change="onDefaultChange" />
					</view> -->
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js';

	export default {
		data() {
			return {
				addressList: [],
				cities: [], // 城市列表
				districts: [], // 区县列表
				cityIndex: -1,
				districtIndex: -1,
				form: {
					id: null,
					userName: '',
					phone: '',
					cityId: null,
					cityName: '',
					districtId: null,
					districtName: '',
					address: '',
					defaultAddress: 0
				},
				isEdit: false,
				dialogTitle: '添加地址'
			};
		},
		async onShow() {
			await this.loadAddressList();
			await this.loadCities(); // 加载城市数据
		},
		methods: {
			async loadCities() {
				try {
					const res = await request({
						url: "warehouse/queryCities",
						method: "GET"
					});

					if (res.code === 200) {
						this.cities = res.data;
					}
				} catch (error) {
					console.error("加载城市列表失败:", error);
				}
			},

			async loadDistricts(cityId) {
				try {
					const res = await request({
						url: `warehouse/queryDistricts/${cityId}`,
						method: "GET"
					});

					if (res.code === 200) {
						this.districts = res.data;
					}
				} catch (error) {
					console.error("加载区县列表失败:", error);
				}
			},

			onCityChange(e) {
				const index = e.detail.value;
				if (index >= 0 && index < this.cities.length) {
					this.form.cityId = this.cities[index].id;
					this.form.cityName = this.cities[index].name;
					this.cityIndex = index;
					this.loadDistricts(this.form.cityId); // 加载对应区县

					// 重置区县选择
					this.form.districtId = null;
					this.form.districtName = '';
					this.districtIndex = -1;
				}
			},

			onDistrictChange(e) {
				const index = e.detail.value;
				if (index >= 0 && index < this.districts.length) {
					this.form.districtId = this.districts[index].id;
					this.form.districtName = this.districts[index].name;
					this.districtIndex = index;
				}
			},

			async editAddress(id) {
				try {
					const res = await request({
						url: `address/queryAddressById/${id}`,
						method: "GET"
					});

					if (res.code === 200) {
						this.form = {
							id: res.data.id,
							userName: res.data.userName,
							phone: res.data.phone,
							cityId: res.data.cityId,
							districtId: res.data.districtId,
							address: res.data.address,
							defaultAddress: res.data.defaultAddress
						};

						// 加载对应的区县数据
						if (this.form.cityId) {
							await this.loadDistricts(this.form.cityId);
							// 设置当前选择的城市和区县索引
							this.cityIndex = this.cities.findIndex(c => c.id === this.form.cityId);
							this.districtIndex = this.districts.findIndex(d => d.id === this.form.districtId);
						}

						this.isEdit = true;
						this.dialogTitle = '修改地址';
						this.$refs.addressDialog.open();
					}
				} catch (error) {
					console.error("获取地址详情失败:", error);
				}
			},

			async submitAddress() {
				if (!this.validateForm()) return;

				try {
					const url = this.isEdit ? "address/updateAddress" : "address/addAddress";
					const method = "POST";

					// 添加城市和区县名称到表单数据
					const cityObj = this.cities.find(c => c.id === this.form.cityId) || {};
					const districtObj = this.districts.find(d => d.id === this.form.districtId) || {};
					
					const submitData = {
						...this.form,
						cityName: cityObj.name || '',
						districtName: districtObj.name || ''
					};

					await request({
						url,
						method,
						data: submitData
					});

					uni.showToast({
						title: this.isEdit ? '修改成功' : '添加成功',
						icon: 'success'
					});

					await this.loadAddressList();
					this.$refs.addressDialog.close();
				} catch (error) {
					console.error("操作失败:", error);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},

			validateForm() {
				if (!this.form.userName) {
					uni.showToast({
						title: '请填写收货人姓名',
						icon: 'none'
					});
					return false;
				}

				// if (!this.form.phone || !/^1[3-9]\d{9}$/.test(this.form.phone)) {
				// 	uni.showToast({
				// 		title: '请填写正确的手机号',
				// 		icon: 'none'
				// 	});
				// 	return false;
				// }

				if (!this.form.cityId) {
					uni.showToast({
						title: '请选择城市',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.districtId) {
					uni.showToast({
						title: '请选择区县',
						icon: 'none'
					});
					return false;
				}

				if (!this.form.address) {
					uni.showToast({
						title: '请填写详细地址',
						icon: 'none'
					});
					return false;
				}

				return true;
			},

			async loadAddressList() {
				try {
					const res = await request({
						url: "address/queryAddressByUserId",
						method: "GET"
					});

					if (res.code === 200) {
						// 将默认地址排在最前面
						this.addressList = res.data.sort((a, b) => b.defaultAddress - a.defaultAddress);
					}
				} catch (error) {
					console.error("加载地址列表失败:", error);
					uni.showToast({
						title: '加载地址失败',
						icon: 'none'
					});
				}
			},

			showAddDialog() {
				this.resetForm();
				this.isEdit = false;
				this.dialogTitle = '添加地址';
				this.$refs.addressDialog.open();
			},

			onDefaultChange(e) {
				this.form.defaultAddress = e.detail.value ? 1 : 0;
			},

			resetForm() {
				this.form = {
					id: null,
					userName: '',
					phone: '',
					cityId: null,
					cityName: '',
					districtId: null,
					districtName: '',
					address: '',
					defaultAddress: 0
				};
				this.cityIndex = -1;
				this.districtIndex = -1;
			},

			async deleteAddress(id) {
				try {
					uni.showModal({
						title: '提示',
						content: '确定要删除该地址吗？',
						success: async (res) => {
							if (res.confirm) {
								await request({
									url: `address/deleteAddress/${id}`,
									method: "GET"
								});

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});

								await this.loadAddressList();
							}
						}
					});
				} catch (error) {
					console.error("删除地址失败:", error);
				}
			},

			async setDefaultAddress(id) {
				try {
					await request({
						url: `address/changeDefaultAddress/${id}`,
						method: "GET"
					});

					uni.showToast({
						title: '设置默认地址成功',
						icon: 'success'
					});

					await this.loadAddressList();
				} catch (error) {
					console.error("设置默认地址失败:", error);
				}
			}
		}
	};
</script>

<style>
	.address-form {
		padding: 20rpx;
	}

	.form-row {
		margin-bottom: 30rpx;
	}

	.form-label {
		display: block;
		margin-bottom: 10rpx;
		color: #666;
		font-size: 28rpx;
	}

	.form-input,
	.form-textarea {
		border: 1rpx solid #eee;
		padding: 20rpx;
		border-radius: 8rpx;
		width: 100%;
		box-sizing: border-box;
	}

	.form-textarea {
		height: 150rpx;
	}

	.form-picker {
		border: 1rpx solid #eee;
		padding: 20rpx;
		border-radius: 8rpx;
	}

	.picker-content {
		color: #333;
	}

	.switch-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.my-address {
		padding: 20rpx;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.address-list {
		flex: 1;
		margin-bottom: 100rpx;
	}

	.address-item {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.default-address {
		border-left: 8rpx solid #ff6700;
	}

	.address-header {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
	}

	.user-name {
		font-weight: bold;
		margin-right: 20rpx;
	}

	.phone {
		color: #666;
		margin-right: 20rpx;
	}

	.default-tag {
		background-color: #ff6700;
		color: #fff;
		font-size: 22rpx;
		padding: 0 10rpx;
		border-radius: 4rpx;
	}

	.address-detail {
		color: #333;
		margin-bottom: 20rpx;
	}

	.address-actions {
		display: flex;
		justify-content: flex-end;
	}

	.address-actions button {
		margin-left: 20rpx;
		font-size: 26rpx;
		padding: 0 20rpx;
		height: 50rpx;
		line-height: 50rpx;
	}

	.edit-btn {
		background-color: #f0f0f0;
		color: #333;
	}

	.delete-btn {
		background-color: #f0f0f0;
		color: #ff0000;
	}

	.set-default-btn {
		background-color: #f0f0f0;
		color: #ff6700;
	}

	.add-btn-container {
		position: fixed;
		bottom: 30rpx;
		left: 0;
		right: 0;
		padding: 0 20rpx;
	}

	.add-btn {
		background-color: #ff6700;
		color: #fff;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
	}
</style>